package com.example.common.network;

import android.content.Context;
import android.content.SharedPreferences;
import com.example.common.utils.LogUtil;

public class TokenManager {
    
    private static volatile TokenManager instance;
    private SharedPreferences sharedPreferences;
    
    private static final String PREFS_NAME = "token_prefs";
    private static final String KEY_ACCESS_TOKEN = "access_token";
    private static final String KEY_REFRESH_TOKEN = "refresh_token";
    private static final String KEY_TOKEN_TYPE = "token_type";
    private static final String KEY_EXPIRES_IN = "expires_in";
    private static final String KEY_TOKEN_SAVE_TIME = "token_save_time";
    
    private TokenManager(Context context) {
        sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    }
    
    public static void init(Context context) {
        if (instance == null) {
            synchronized (TokenManager.class) {
                if (instance == null) {
                    instance = new TokenManager(context.getApplicationContext());
                }
            }
        }
    }
    
    public static TokenManager getInstance() {
        if (instance == null) {
            throw new IllegalStateException("TokenManager must be initialized first");
        }
        return instance;
    }
    
    /**
     * 保存Token信息
     */
    public void saveToken(String accessToken, String refreshToken, String tokenType, long expiresIn) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_ACCESS_TOKEN, accessToken);
        editor.putString(KEY_REFRESH_TOKEN, refreshToken);
        editor.putString(KEY_TOKEN_TYPE, tokenType != null ? tokenType : "Bearer");
        editor.putLong(KEY_EXPIRES_IN, expiresIn);
        editor.putLong(KEY_TOKEN_SAVE_TIME, System.currentTimeMillis());
        editor.apply();
        
        LogUtil.d("TokenManager", "Token saved successfully");
    }
    
    /**
     * 获取访问令牌
     */
    public String getAccessToken() {
        return sharedPreferences.getString(KEY_ACCESS_TOKEN, null);
    }
    
    /**
     * 获取刷新令牌
     */
    public String getRefreshToken() {
        return sharedPreferences.getString(KEY_REFRESH_TOKEN, null);
    }
    
    /**
     * 获取Token类型
     */
    public String getTokenType() {
        return sharedPreferences.getString(KEY_TOKEN_TYPE, "Bearer");
    }
    
    /**
     * 获取完整的Authorization头值
     */
    public String getAuthorizationHeader() {
        String accessToken = getAccessToken();
        if (accessToken == null || accessToken.isEmpty()) {
            return null;
        }
        String tokenType = getTokenType();
        return tokenType + " " + accessToken;
    }
    
    /**
     * 检查Token是否过期
     */
    public boolean isTokenExpired() {
        long expiresIn = sharedPreferences.getLong(KEY_EXPIRES_IN, 0);
        long saveTime = sharedPreferences.getLong(KEY_TOKEN_SAVE_TIME, 0);
        
        if (expiresIn == 0 || saveTime == 0) {
            return true;
        }
        
        long currentTime = System.currentTimeMillis();
        long expirationTime = saveTime + (expiresIn * 1000);
        
        // 提前5分钟判断为过期，给刷新Token留出时间
        return currentTime >= (expirationTime - 5 * 60 * 1000);
    }
    
    /**
     * 检查是否有有效Token
     */
    public boolean hasValidToken() {
        String accessToken = getAccessToken();
        return accessToken != null && !accessToken.isEmpty() && !isTokenExpired();
    }
    
    /**
     * 清除Token信息
     */
    public void clearToken() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove(KEY_ACCESS_TOKEN);
        editor.remove(KEY_REFRESH_TOKEN);
        editor.remove(KEY_TOKEN_TYPE);
        editor.remove(KEY_EXPIRES_IN);
        editor.remove(KEY_TOKEN_SAVE_TIME);
        editor.apply();
        
        LogUtil.d("TokenManager", "Token cleared");
    }
    
    /**
     * 更新访问令牌（刷新Token时使用）
     */
    public void updateAccessToken(String newAccessToken, long expiresIn) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_ACCESS_TOKEN, newAccessToken);
        editor.putLong(KEY_EXPIRES_IN, expiresIn);
        editor.putLong(KEY_TOKEN_SAVE_TIME, System.currentTimeMillis());
        editor.apply();
        
        LogUtil.d("TokenManager", "Access token updated");
    }
}